import './imports.js';
import { getUrlQueryValue } from '../libs/utils';

import Header from '../components/Header';
import NewsFrame from '../components/Iframe/index.js';
import Collector from '../components/Collector/index.js';

;((doc) => {
    const oApp = doc.querySelector('#app');
    const currentNews = JSON.parse(localStorage.getItem('currentNews'));
    const collectorDataList = JSON.parse(localStorage.getItem('collectorDataList') || "[]");

    const init = () => {
        render();
        bindEvent();
    }

    function render(){
        const headerTpl = Header.tpl({
            url: getUrlQueryValue('path'),
            title: '新闻详情页',
            showLeftIcon: true,
            showRightIcon: false
        })

        const newsFrameTpl = NewsFrame.tpl(currentNews.url);
        const collectorTpl = isCollector();

        oApp.innerHTML += (headerTpl + newsFrameTpl + collectorTpl );  
    };

    function bindEvent(){
        Collector.bindEvent(doCollector);
    }

    function isCollector(){
        const isExist = collectorDataList.find((item) => item.uniquekey === currentNews.uniquekey );
        return isExist ? Collector.collector() : Collector.unCollector();
    }   

    function doCollector(status){
        let collectorDataList = JSON.parse(localStorage.getItem('collectorDataList') || '[]');
        if(status){
            collectorDataList.push(currentNews);
        }else{
            console.log(currentNews.uniquekey);
            collectorDataList = collectorDataList.filter(item => item.uniquekey !== currentNews.uniquekey);
        }

        localStorage.setItem('collectorDataList',JSON.stringify(collectorDataList));
    }

    init();
})(document);